#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/4/29 1:22 下午
# @Author  : adam

import pymongo
from bson.objectid import ObjectId

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

dblist = myclient.list_database_names()
if "test" in dblist:
    print("数据库存在")
mydb = myclient["test"]
collist = mydb.list_collection_names()

if "test" in collist:
    print("集合存在")
    mycol = mydb["test"]
    obj_o=mycol.find_one()
    print(obj_o)

    # for x in mycol.find():
    #     print(x)

    obj_all=mycol.find().sort("_id")
    for i in obj_all:
        print(i)
else:
    mycol = mydb["sites"]
    mydict = {"name": "RUNOOB", "alexa": "10000", "url": "https://www.runoob.com"}
    x = mycol.insert_one(mydict)
    print(x.inserted_id)

    mylist = [
        {"_id": 1,"name": "Taobao", "alexa": "100", "url": "https://www.taobao.com"},
        {"_id": 2,"name": "QQ", "alexa": "101", "url": "https://www.qq.com"},
        {"_id": 3,"name": "Facebook", "alexa": "10", "url": "https://www.facebook.com"},
        {"_id": 4,"name": "知乎", "alexa": "103", "url": "https://www.zhihu.com"},
        {"name": "Github", "alexa": "109", "url": "https://www.github.com"}
    ]

    y = mycol.insert_many(mylist)
    print(y.inserted_ids)